import React, { useState, useEffect, useRef } from 'react';
import { Switch, Button, Spin, message } from 'antd';
import axios from 'axios'; // 假设使用axios发送请求
import StockPolling from './StockPolling';
import StockPollingPage from './StockPollingPage';
import OrderStatusPolling from './OrderStatusPolling';
import UploadProgressPolling from './UploadProgressPolling';

const PollingDemo = () => {
  // 轮询状态管理
  const [isPolling, setIsPolling] = useState(false); // 轮询开关状态
  const [pollingData, setPollingData] = useState(null); // 轮询数据
  const [isLoading, setIsLoading] = useState(false); // 加载状态
  const timerRef = useRef(null); // 定时器引用

  // 轮询间隔（毫秒）
  const POLLING_INTERVAL = 3000; // 3秒

  const [showCpn, setShowCpn] = useState(null);

  // 模拟轮询请求（实际替换为真实接口）
  const fetchData = async () => {
    setIsLoading(true);
    try {
      const response = await axios.get('http://123.207.32.32:9002/dj/catelist');
      setPollingData(response.data);
      message.success('数据获取成功');
    } catch (error) {
      message.error('数据获取失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 启动轮询
  const startPolling = () => {
    setIsPolling(true);
    fetchData(); // 首次请求
    timerRef.current = setInterval(() => {
      fetchData(); // 定时请求
    }, POLLING_INTERVAL);
  };

  // 停止轮询
  const stopPolling = () => {
    setIsPolling(false);
    clearInterval(timerRef.current); // 清除定时器
  };

  // 组件卸载时清除定时器
  useEffect(() => {
    return () => {
      stopPolling();
    };
  }, []);

  const onClickBtn = (type) => {
    let cpn
    switch (type) {
      case 'stock':
        cpn = <StockPolling />;
        break
      case 'stock-page':
        cpn = <StockPollingPage />;
        break
      case 'order':
        cpn = <OrderStatusPolling />;
        break
      case 'upload':
        cpn = <UploadProgressPolling />;
        break
      default:
        return null;
    }
    setShowCpn(cpn)
  }

  return (
    <div style={{ padding: 20 }}>
      <h3>轮询请求控制</h3>
      <Switch
        checked={isPolling}
        onChange={(checked) => {
          checked ? startPolling() : stopPolling();
        }}
        checkedChildren="开启轮询"
        unCheckedChildren="关闭轮询"
      />

      {isPolling && (
        <Spin spinning={isLoading} style={{ marginLeft: 16 }}>
          轮询中（每{POLLING_INTERVAL / 1000}秒请求一次）
        </Spin>
      )}

      <div style={{ marginTop: 24 }}>
        {pollingData && (
          <div>
            <h4>最新轮询数据：</h4>
            <pre>{JSON.stringify(pollingData, null, 2)}</pre>
          </div>
        )}
      </div>

      {/* 手动触发请求按钮（可选） */}
      <Button
        type="primary"
        onClick={fetchData}
        disabled={isLoading}
        style={{ marginTop: 16 }}
      >
        {isLoading ? '加载中...' : '手动获取数据'}
      </Button>

      <h3 style={{ marginTop: 40 }}>其他示例</h3>
      {/* 添加其他示例组件 */}
      <Button onClick={() => onClickBtn('stock')}>实时股票信息</Button>
      <Button onClick={() => onClickBtn('stock-page')}>实时股票信息-分页</Button>
      <Button onClick={() => onClickBtn('order')}>订单状态信息</Button>
      <Button onClick={() => onClickBtn('upload')}>文件上传进度信息</Button>

      {showCpn}
    </div>
  );
};

export default PollingDemo;